package cn.edu.swu.miniwebsvr.core;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class Router {
    // [222024321072041/王耀东] 根据请求的URL获取Handler
    public void route(Parameter request, OutputStream response){
        Config config = Config.getInstance();
        Handler handler = config.getHandler(request.getUrl());

        if (handler == null){
            handler = config.getHandler("/");
        } else if (handler != null){
            handler.handle(request,response);
        } else {
            sendErrorResponse(response);
        }

    }

    private void sendErrorResponse(OutputStream response){
        try {
            String errorResponse = "HTTP/1.1 500 Internal Server Error\r\n" +
                    "Content-Type: text/html\r\n" +
                    "\r\n" +
                    "<html><body><h1>" +"500 Internal Server Error" + "</h1></body></html>";
            response.write(errorResponse.getBytes(StandardCharsets.UTF_8));
            response.flush();
        } catch (IOException e){
            e.printStackTrace();
        }
    }



}
